package com.logic.landseaserver.service.callback;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.logic.landseaserver.common.LandeaConstants.DdingConstant;
import com.logic.landseaserver.common.LandseaErrorMessageEnum;
import com.logic.landseaserver.common.config.SendMsgConfiguration;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.domain.AbstractCallbackEvt;
import com.logic.landseaserver.domain.DdingEventCallbackEvt;
import com.logic.landseaserver.domain.DdingRoomSync;
import com.logic.landseaserver.models.ddlock.DdingLockEvtService;
import com.logic.landseaserver.persistence.read.DdingRoomSyncReadMapper;
import com.logic.landseaserver.persistence.write.DdingRoomSyncWriteMapper;
import com.logic.system.service.IConfigurationService;

/**
 * 
 * 项目名称：system-server</br>
 * 类名称：DdingLockOfflineAlarmEvtHandler</br>
 * 类描述：电池电量回调</br>
 * 创建人：Aaron</br>
 * 创建时间：2017年10月23日 下午2:39:43</br>
 * 
 * @version 1.0
 *
 */
@Service(DdingConstant.CALLBACK_EVNET_SERVICE_NAME_PREFIX + "batteryAsync")
public class DdingLockBatteryAsyncEvtHandler implements IEventCallbackHandler
{
    private static final Logger LOG = LoggerFactory.getLogger(DdingLockBatteryAsyncEvtHandler.class);
    
    @Autowired
    private DdingRoomSyncReadMapper ddingRoomSyncReadMapper;
    
    @Autowired
    private DdingRoomSyncWriteMapper ddingRoomSyncWriteMapper;
    
    @Autowired
    private DdingLockEvtService ddingLockEvtService;
    
    @Autowired
    private SendMsgConfiguration sendMsgConfiguration;
    
    @Autowired
    private IConfigurationService configurationService;
    
    @SuppressWarnings("unchecked")
    @Override
    public Object process(AbstractCallbackEvt callbackEvent)
        throws LandseaException
    {
        try
        {
            DdingEventCallbackEvt event = (DdingEventCallbackEvt)callbackEvent;
            String roomIdStr = event.getRoom_id();
            if (StringUtils.isEmpty(roomIdStr))
            {
                LOG.error("云丁事件回调|电池电量回调|room_id为空，消息丢弃处理.");
                throw LandseaException.createException(LandseaErrorMessageEnum.DDINGLOCK_ROOM_NONESYNC_ERROR);
            }
            
            Object detailObject = event.getDetail();
            if (null == detailObject)
            {
                LOG.error("云丁事件回调|电池电量回调|detail为空.");
                throw LandseaException.createException(LandseaErrorMessageEnum.DDINGLOCK_CALLBACK_PARAM_ERROR);
            }
            Map<String, Object> detailMap = (Map<String, Object>)detailObject;
            Object battery = detailMap.get("battery");
            if (null == battery)
            {
                LOG.error("云丁事件回调|电池电量回调|battery为空.");
                throw LandseaException.createException(LandseaErrorMessageEnum.DDINGLOCK_CALLBACK_PARAM_ERROR);
            }
            Integer batteryInt = (Integer)battery;
            processLowBattery(roomIdStr, batteryInt);
            return null;
        }
        catch (LandseaException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            LOG.error("云丁事件回调|电池电量回调|处理消息发生错误.", e);
            throw LandseaException.createException(LandseaErrorMessageEnum.DDINGLOCK_CALLBACK_PROCESS_ERROR, e);
        }
    }
    
    private void processLowBattery(String roomIdStr, int batteryInt)
        throws LandseaException
    {
        Integer roomId = Integer.parseInt(roomIdStr);
        
        // 查询房间记录是否存在
        DdingRoomSync ddingRoomSync = ddingRoomSyncReadMapper.selectByPrimaryKey(roomId);
        
        if (null == ddingRoomSync || DdingConstant.SYNCSTATE_YES != ddingRoomSync.getSyncState())
        {
            LOG.error("云丁事件回调|电池电量回调|房间记录不存在roomId=" + roomId);
            throw LandseaException.createException(LandseaErrorMessageEnum.DDINGLOCK_ROOM_NONESYNC_ERROR);
        }
        
        // 电池电量预警伐值
        int warningInt = Integer.parseInt(configurationService.getStringValue("DDING_BATTERY_LOW_VALUE"));
        
        int batteryLowFlag = DdingConstant.ONLINE_UPPERBATTERY;
        String logStr = "充足";
        // 如果电池电量低于伐值，要预警
        if (batteryInt < warningInt)
        {
            batteryLowFlag = DdingConstant.OFFLINE_LOWBATTERY;
            logStr = "低于伐值";
        }
        
        Integer batteryLowDb = ddingRoomSync.getBatteryLow();
        
        // 是否要发送预警短信
        boolean isNeedSendSms = false;
        
        if (null == batteryLowDb)
        {
            if (DdingConstant.OFFLINE_LOWBATTERY == batteryLowFlag)
            {
                // 要发短信
                isNeedSendSms = true;
            }
        }
        else if (DdingConstant.ONLINE_UPPERBATTERY == batteryLowDb.intValue()
            && DdingConstant.OFFLINE_LOWBATTERY == batteryLowFlag)
        {
            isNeedSendSms = true;
        }
        
        DdingRoomSync update = new DdingRoomSync();
        update.setBatteryLow(batteryLowFlag);
        update.setRoomId(roomId);
        update.setBatteryPercentage(batteryInt);
        ddingRoomSyncWriteMapper.updateByPrimaryKeySelective(update);
        LOG.info("房间roomId=" + roomId + "电池电量" + logStr);
        
        if (isNeedSendSms)
        {
            LOG.info("房间roomId=" + roomId + "发送电量预警短信.");
            // 入库短信表，定时任务发送
            ddingLockEvtService.sendSmsToDz(sendMsgConfiguration.getDoorLockbatteryLowCode(),
                ddingRoomSync.getProjectId(),
                roomId);
        }
    }
}
